//
//  LGAddDoctorAdviceController.m
//  HeartDiseaseManage
//
//  Created by Bovin on 2024/8/4.
//  开具医嘱

#import "LGAddDoctorAdviceController.h"
#import "LGAdviceSendSuccesController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "TUIAudioRecorder.h"
#import "TUIRecordView.h"
#import "TUIDefine.h"
#import "TUITool.h"
#import "TUIDefine.h"
#import "MCPlayer.h"
#import "TUIDefine.h"
#import "LGPickerViewMax.h"
#define placeHolder  @"请输入..."
#define lineHeight   viewPix(44)
@interface LGAddDoctorAdviceController ()<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource,AVAudioRecorderDelegate>
/**   */
@property (nonatomic , strong)UIButton *sendBtn;
/**   */
@property (nonatomic , strong)UIScrollView *scrollView;
/**   */
@property (nonatomic , strong)UILabel *contentTitle;
/**   */
@property (nonatomic , strong)UIView *contentView;
/**   */
@property (nonatomic , strong)UITextView *contentTF;
/**   */
@property (nonatomic , strong)UILabel *numberLabel;
/**   */
@property (nonatomic , strong)UILabel *recordTitle;
/**   */
@property (nonatomic , strong)UITableView *recordTable;
/**   */
@property (nonatomic , strong)UIButton *recordBtn;

@property (nonatomic , strong)TUIRecordView *recordView;
/**   */
@property (nonatomic , strong)AVAudioSession *session;
/**   */
@property (nonatomic , strong)AVAudioRecorder *recorder;
/**   */
@property (nonatomic , copy)NSString *filePath;
/**   */
@property (nonatomic , assign)BOOL allowRecord;
/**   */
@property (nonatomic , strong)NSTimer *recordTimer;
/**   */
@property (nonatomic , strong)NSDate *recordStartTime;
/**   */
@property (nonatomic , assign)BOOL firstRecord;
/**   */
@property (nonatomic , strong)NSArray *doctorArray;

@end

@implementation LGAddDoctorAdviceController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.content = @"";
    self.title = @"开具医嘱";
    self.appointid = (_appointid && _appointid.length>0)?_appointid:@"0";
    self.followid = (_followid && _followid.length>0)?_followid:@"0";
    self.source = (_source && _source.length>0)?_source:@"";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.sendBtn];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentTitle];
    [self.scrollView addSubview:self.contentView];
    [self.contentView addSubview:self.contentTF];
    [self.contentView addSubview:self.numberLabel];
    [self.scrollView addSubview:self.recordTitle];
    [self.scrollView addSubview:self.recordTable];
    [self.scrollView addSubview:self.recordBtn];
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.contentView).offset(-viewPix(16));
    }];
    [self.recordTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView.mas_bottom).offset(viewPix(20));
        make.left.equalTo(self.view).offset(viewPix(20));
    }];
    [self.recordTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.recordTitle.mas_bottom).offset(viewPix(4));
        make.left.equalTo(self.view).offset(viewPix(16));
        make.right.equalTo(self.view).offset(-viewPix(16));
        make.height.equalTo(@(lineHeight*2+viewPix(54)));
    }];
    [self.recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.recordTable).offset(-viewPix(12));
        make.width.equalTo(@(viewPix(100)));
        make.height.equalTo(@(viewPix(28)));
    }];
    [self requestData];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[MCPlayer shareManager] stopMedia];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/medical_advice.medical_advice/getCurrentOther" parameters:@{@"patient_id":self.patientid,@"followup_id":self.followid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.adviceid = LGNSString(returnData[@"advice_id"]);
            self.content = returnData[@"content"][@"suggest"];
            self.recordArray = [NSMutableArray arrayWithArray:returnData[@"content"][@"voice"]];
            [self performSelector:@selector(resetScrollHeight) withObject:nil afterDelay:0.3];
            [self.recordTable reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)requestDoctorArray{
    [RequestUtil withPOST:@"/doctor/Select/teamDoctorOptions" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.doctorArray = returnData;
        }
    } error:^(NSError *error) {
        
    }];
}

//保存数据
-(void)saveDataRequest{
    [self.view endEditing:YES];
    if(!_adviceid) return;
    [RequestUtil withPOST:@"/doctor/medical_advice.medical_advice/saveAdviceOther" parameters:@{@"advice_id":self.adviceid,@"followup_id":self.followid,@"suggest":self.content,@"voice":self.recordArray} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        
    } error:^(NSError *error) {
        
    }];
}


//发送医嘱
-(void)sendBtnAction{
    if(self.sendBtn.selected == NO) return;
    [self saveDataRequest];
    __weak typeof(self) weakSelf = self;
    
    //护士、个案管理师发送前要选择医生
    if([kRoleId isEqualToString:@"20"] || [kRoleId isEqualToString:@"30"]){
        if(self.doctorArray.count == 0){
            [self requestDoctorArray];
        }else{
            NSMutableArray *pickerArray = [NSMutableArray array];
            for (NSInteger i=0; i<self.doctorArray.count; i++) {
                NSDictionary *tempDic = self.doctorArray[i];
                [pickerArray addObject:LGNSString(tempDic[@"title"])];
            }
            LGPickerViewMax *pickerView = [[LGPickerViewMax alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
            [pickerView.sureBtn setTitle:@"确定发送" forState:UIControlStateNormal];
            pickerView.titleLabel.text = @"本次开具医嘱的医生";
            pickerView.pickArry = @[pickerArray];
            [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
            pickerView.selectPickViewIndex = ^(NSArray *indexArray) {
                NSInteger index = [indexArray[0] integerValue];
                NSDictionary *doctorDic = weakSelf.doctorArray[index];
                [RequestUtil withPOST:@"/doctor/medical_advice.medical_advice/send" parameters:@{@"patient_id":self.patientid,@"followup_id":self.followid,@"appointment_id":self.appointid,@"source":self.source,@"send_doctor_id":LGNSString(doctorDic[@"value"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
                    if(code == 200){
                        LGAdviceSendSuccesController *controller = [[LGAdviceSendSuccesController alloc]init];
                        controller.patientid = weakSelf.patientid;
                        [weakSelf.navigationController pushViewController:controller animated:YES];
                    }else{
                        [TooltipView showMessage:message offset:0];
                    }
                } error:^(NSError *error) {
                    [TooltipView showMessage:LGErrorMessage offset:0];
                }];
            };
        }
    }else{
        [LGAlertTool alertWithTitle:@"发送医嘱" content:@"确定发送给患者？" sureAction:^{
            [RequestUtil withPOST:@"/doctor/medical_advice.medical_advice/send" parameters:@{@"patient_id":self.patientid,@"followup_id":self.followid,@"appointment_id":self.appointid,@"source":self.source,@"send_doctor_id":kUserId} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
                if(code == 200){
                    LGAdviceSendSuccesController *controller = [[LGAdviceSendSuccesController alloc]init];
                    controller.patientid = weakSelf.patientid;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                }else{
                    [TooltipView showMessage:message offset:0];
                }
            } error:^(NSError *error) {
                [TooltipView showMessage:LGErrorMessage offset:0];
            }];
        }];
    }
}


-(void)setContent:(NSString *)content{
    _content = content;
    if((content.length == 0 || [content isEqualToString:placeHolder])&&self.contentTF.isFirstResponder == NO){
        self.contentTF.text = placeHolder;
        self.contentTF.textColor = [UIColor colorWithString:@"#999999"];
    }else{
        self.contentTF.textColor = [UIColor colorWithString:@"#333333"];
    }
    if(content.length>0){
        self.contentTF.attributedText = [content attributeString:@{NSFontAttributeName:LGFont(16),NSForegroundColorAttributeName:[UIColor colorWithString:@"#333333"]} lineSpacing:3];
    }
    CGSize maxSize = CGSizeMake(self.contentTF.size.width, MAXFLOAT);
    CGSize fitSize = [self.contentTF sizeThatFits:maxSize];
    CGFloat viewHeight = self.contentTF.bounds.size.height;
    CGFloat newHeight = fitSize.height;
    NSLog(@">>>???>>>%.2f--%.2f",newHeight,viewHeight);
    if(newHeight > viewPix(100) && newHeight != viewHeight){
        self.contentView.frame = CGRectMake(viewPix(16), viewPix(42), Screen_W-viewPix(32), newHeight+viewPix(50));
        self.contentTF.frame = CGRectMake(viewPix(12), viewPix(6), Screen_W-viewPix(56), newHeight+5);
        [self resetScrollHeight];
    }
    self.numberLabel.text = [NSString stringWithFormat:@"%ld/500",content.length];
    self.sendBtn.selected = (content.length == 0 && self.recordArray.count == 0)?NO:YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    self.contentTF.textColor = [UIColor colorWithString:@"#333333"];
    if([textView.text isEqualToString:placeHolder]){
        self.contentTF.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    self.content = textView.text;
    [self saveDataRequest];
    [self resetScrollHeight];
}

- (void)textViewDidChange:(UITextView *)textView{
    self.hasEdit = YES;
    NSString *lang = textView.textInputMode.primaryLanguage; // 键盘输入模式
    NSString *content = textView.text;
    if ([lang isEqualToString:@"zh-Hans"]){
        UITextRange *selectedRange = [textView markedTextRange];
        if (!selectedRange) { // 没有高亮
            self.content = (textView.text.length>500)?[textView.text substringToIndex:500]:textView.text;
        }
    }else{
        self.content = (textView.text.length>500)?[textView.text substringToIndex:500]:textView.text;
    }
}


//开始录音
- (void)onRecordButtonTouchDown:(UIButton *)sender{
    self.allowRecord = NO;
    @weakify(self)
    [self requestRecordAuthorization:^(BOOL first, BOOL granted) {
        @strongify(self)
        if(first == NO && granted == NO){
            //拒绝录音--弹框去开启录音
            [self showRecordAuthorizationAlert];
        }else if(first == NO && granted == YES){
            //允许录音
            self.allowRecord = YES;
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
            
            NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"record_file"];
            // 判断文件夹是否存在
            if(![[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil] count]){
                [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            }
            self.filePath = [path stringByAppendingPathComponent:@"/record.m4a"];
            NSDictionary *recordSetting = [[NSDictionary alloc]
                initWithObjectsAndKeys:
                        [NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                        [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                        [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                        [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                        [NSNumber numberWithInt:AVAudioQualityHigh], AVEncoderAudioQualityKey, nil];

            self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:self.filePath] settings:recordSetting error:nil];
            self.recorder.meteringEnabled = YES;
            [self.recorder prepareToRecord];
            [self.recorder record];
            [self.recorder updateMeters];
            self.recordStartTime = [NSDate date];
            self.recordTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onRecordTimerTriggered:) userInfo:nil repeats:YES];
            [self.view.window addSubview:self.recordView];
        }
    }];
}


//录音计时器
-(void)onRecordTimerTriggered:(NSTimer *)timer{
    [self.recorder updateMeters];
    float power = [self.recorder averagePowerForChannel:0];
    [self.recordView setPower:power];
}

//结束录音
- (void)onRecordButtonTouchUpInside:(UIButton *)sender{
    if(!_recordTimer){
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [self.recorder stop];
            if (self.recordTimer) {
                [self.recordTimer invalidate];
                self.recordTimer = nil;
            }
            [self.recordView setStatus:Record_Status_TooShort];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self);
                [UIView animateWithDuration:0.3 animations:^{
                    self.recordView.alpha = 0;
                } completion:^(BOOL finished) {
                    [self.recordView removeFromSuperview];
                    self.recordView = nil;
                }];
            });
        });
    }else{
        [self.recorder stop];
        if (_recordTimer) {
            [self.recordTimer invalidate];
            self.recordTimer = nil;
        }
        NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:self.recordStartTime];
        @weakify(self);
        if (interval == NAN || interval < 1) {
            [self.recordView setStatus:Record_Status_TooShort];

        }else{
            self.recordView.title.text = @"录音完成";
            self.recordView.title.backgroundColor = [UIColor clearColor];
            [self saveRecordData:sender];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [UIView animateWithDuration:0.3 animations:^{
                self.recordView.alpha = 0;
            } completion:^(BOOL finished) {
                [self.recordView removeFromSuperview];
                self.recordView = nil;
            }];
        });
    }
}

-(void)onRecordButtonTouchCancel:(UIButton *)sender{
    if ([self.recorder isRecording]) [self.recorder stop];
    if (_recordTimer) {
        [self.recordTimer invalidate];
        self.recordTimer = nil;
    }
    [self.recordView removeFromSuperview];
    self.recordView = nil;
}

//上滑结束
- (void)onRecordButtonTouchDragExit:(UIButton *)sender{
    [self.recordView setStatus:Record_Status_Cancel];
}

//滑入录音
- (void)onRecordButtonTouchDragEnter:(UIButton *)sender{
    [self.recordView setStatus:Record_Status_Recording];
}



//保存录音数据
-(void)saveRecordData:(UIButton *)sender{
    if(self.allowRecord == NO) return;
    __block NSInteger index = sender.tag;
    
    NSData *data = [NSData dataWithContentsOfFile:self.filePath];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:self.filePath] options:nil];
    __block CGFloat second = CMTimeGetSeconds(asset.duration);
    [RequestUtil uploadVoice:@"/doctor/upload/audio" parameters:@{@"to_text":@"1"} withSign:YES voiceData:@[data] success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            NSDictionary *tempDic = @{@"duration":[NSString stringWithFormat:@"%.f",second],@"url":LGNSString(returnData[@"url"]),@"text":LGNSString(returnData[@"text"]),@"file_uri":LGNSString(returnData[@"uri"])};
            [[NSFileManager defaultManager] removeItemAtPath:self.filePath error:nil];
            [self.recordArray addObject:tempDic];
            [self.recordTable reloadData];
            [self resetScrollHeight];
            self.sendBtn.selected = (self.content.length == 0 && self.recordArray.count == 0)?NO:YES;
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } failure:^(NSError *error) {
        [TooltipView showMessage:@"保存失败" offset:0];
    }];
}

//请求录音权限
- (void)requestRecordAuthorization:(void (^)(BOOL first , BOOL granted))response {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    AVAudioSessionRecordPermission permission = session.recordPermission;
    if (permission == AVAudioSessionRecordPermissionUndetermined) {
        [session requestRecordPermission:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (response) {
                    response(YES,NO);
                }
            });
        }];
    } else if (permission == AVAudioSessionRecordPermissionGranted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(NO,YES);
            }
        });
    } else if (permission == AVAudioSessionRecordPermissionDenied) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(NO,NO);
            }
        });
    }
}

//开启权限弹框
- (void)showRecordAuthorizationAlert{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:TUIKitLocalizableString(TUIKitInputNoMicTitle) message:TUIKitLocalizableString(TUIKitInputNoMicTips) preferredStyle:UIAlertControllerStyleAlert];
    [controller tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitInputNoMicOperateLater) style:UIAlertActionStyleCancel handler:nil]];
    [controller tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitInputNoMicOperateEnable) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
    }]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:controller animated:YES completion:nil];
    });
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.recordArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGAdviceOtherRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.recordArray[indexPath.row];
    cell.index = indexPath.row;
    __weak typeof(self) weakSelf = self;
    cell.deleteRecordAtIndex = ^(NSInteger index) {
        [weakSelf.recordArray removeObjectAtIndex:index];
        [weakSelf.recordTable reloadData];
        [weakSelf resetScrollHeight];
        weakSelf.sendBtn.selected = (weakSelf.content.length == 0 && weakSelf.recordArray.count == 0)?NO:YES;
    };
    cell.playRecordAtIndex = ^(NSInteger index) {
        NSDictionary *tempDic = self.recordArray[index];
        MCPlayer *player = [MCPlayer shareManager];
        [player playMediaWithUrl:LGNSString(tempDic[@"url"]) tempPath:nil desPath:nil delegate:self];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}

//重置高度
-(void)resetScrollHeight{
    self.hasEdit = YES;
    //录音
    NSInteger count = self.recordArray.count>2?self.recordArray.count:2;
    [self.recordTable mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(lineHeight*count+viewPix(50)));
    }];
    CGFloat height = kMinY(self.recordTable.frame)+lineHeight*count+viewPix(100);
    height = (height>self.view.bounds.size.height)?height:self.view.bounds.size.height;
    self.scrollView.contentSize = CGSizeMake(Screen_W, height);
}



-(UIButton *)sendBtn{
    if(!_sendBtn){
        _sendBtn = [UIButton buttonWithTitle:@"发送给患者" titleFont:LGFontWeight(14, UIFontWeightMedium) normalColor:@"#666666" selectColor:@"#429BFF"];
        _sendBtn.frame = CGRectMake(Screen_W-viewPix(90), statusBarHeight, viewPix(74), 44);
        _sendBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_sendBtn addTarget:self action:@selector(sendBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

-(UIScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight)];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.bounces = YES;
    }
    return _scrollView;
}


-(UILabel *)contentTitle{
    if(!_contentTitle){
        _contentTitle = [UILabel lableWithText:@"文字医嘱" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _contentTitle.frame = CGRectMake(viewPix(20), viewPix(12), 120, 23);
    }
    return _contentTitle;
}

-(UIView *)contentView{
    if(!_contentView){
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), viewPix(42), Screen_W-viewPix(32), viewPix(150))];
        _contentView.layer.borderColor = [UIColor colorWithString:@"#E3E3E3"].CGColor;
        _contentView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
        _contentView.layer.borderWidth = 0.5;
        _contentView.cornerRidus = 15;
    }
    return _contentView;
}

-(UITextView *)contentTF{
    if(!_contentTF){
        _contentTF = [[UITextView alloc]initWithFrame:CGRectMake(viewPix(12), viewPix(6), Screen_W-viewPix(56), viewPix(100))];
        _contentTF.tintColor = [UIColor colorWithString:@"#333333"];
        _contentTF.textColor = [UIColor colorWithString:@"#999999"];
        _contentTF.textAlignment = NSTextAlignmentLeft;
        _contentTF.scrollEnabled = NO;
        _contentTF.text = placeHolder;
        _contentTF.font = LGFont(16);
        _contentTF.cornerRidus = 5;
        _contentTF.delegate = self;
    }
    return _contentTF;
}

-(UILabel *)numberLabel{
    if(!_numberLabel){
        _numberLabel = [UILabel lableWithText:@"0/500" colorString:@"#999999" textFont:LGFont(14) textAlignment:NSTextAlignmentRight lines:1];
    }
    return _numberLabel;
}

-(UILabel *)recordTitle{
    if(!_recordTitle){
        _recordTitle = [UILabel lableWithText:@"语音医嘱" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _recordTitle;
}

-(UITableView *)recordTable{
    if(!_recordTable){
        _recordTable = [[UITableView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.contentView.frame)+viewPix(45), Screen_W-viewPix(32), viewPix(200)) style:UITableViewStyleGrouped];
        [_recordTable registerClass:[LGAdviceOtherRecordCell class] forCellReuseIdentifier:@"cell"];
        _recordTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _recordTable.rowHeight = viewPix(44);
        _recordTable.backgroundColor = [UIColor whiteColor];
        _recordTable.showsVerticalScrollIndicator = NO;
        _recordTable.cornerRidus = 15;
        _recordTable.dataSource = self;
        _recordTable.delegate = self;
        _recordTable.scrollEnabled = NO;
        _recordTable.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W-viewPix(32), viewPix(12))];
    }
    return _recordTable;
}

-(UIButton *)recordBtn{
    if(!_recordBtn){
        _recordBtn = [UIButton buttonWithTitle:@"  长按录音" titleFont:LGFontWeight(14, UIFontWeightMedium) textColor:@"#FFFFFF" imageName:@"处理意见-长按录音"];
        _recordBtn.backgroundColor = [UIColor colorWithString:@"#3291FF"];
        _recordBtn.cornerRidus = viewPix(14);
        [_recordBtn addTarget:self action:@selector(onRecordButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_recordBtn addTarget:self action:@selector(onRecordButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_recordBtn addTarget:self action:@selector(onRecordButtonTouchCancel:) forControlEvents:UIControlEventTouchUpOutside|UIControlEventTouchCancel];
        [_recordBtn addTarget:self action:@selector(onRecordButtonTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
        [_recordBtn addTarget:self action:@selector(onRecordButtonTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
    }
    return _recordBtn;
}

- (TUIRecordView *)recordView{
    if (!_recordView) {
        _recordView = [[TUIRecordView alloc] init];
        _recordView.frame = [UIScreen mainScreen].bounds;
    }
    return _recordView;
}

-(NSMutableArray *)recordArray{
    if(!_recordArray){
        _recordArray = [NSMutableArray array];
    }
    return _recordArray;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end




@interface LGAdviceOtherRecordCell()

/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UIImageView *iconView;
/**   */
@property (nonatomic , strong)UILabel *durationLabel;
/**   */
@property (nonatomic , strong)UIButton *deleteBtn;

@end


@implementation LGAdviceOtherRecordCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createSubView];
    }
    return  self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.durationLabel.text = [NSString stringWithFormat:@"%@\"",dataDic[@"duration"]];
}

-(void)deleteBtnAction{
    if(self.deleteRecordAtIndex){
        self.deleteRecordAtIndex(self.index);
    }
}

-(void)playRecordAction{
    if(self.playRecordAtIndex){
        self.playRecordAtIndex(self.index);
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    [self.contentView addSubview:self.baseView];
    [self.baseView addSubview:self.iconView];
    [self.baseView addSubview:self.durationLabel];
    [self.baseView addSubview:self.deleteBtn];
}
-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(12), viewPix(6), viewPix(175), viewPix(32))];
        _baseView.backgroundColor = [UIColor colorWithString:@"#0199FE"];
        _baseView.cornerRidus = 4;
        [_baseView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playRecordAction)]];
    }
    return _baseView;
}

-(UIImageView *)iconView{
    if(!_iconView){
        _iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"处理意见-播放录音"]];
        _iconView.frame = CGRectMake(viewPix(10), viewPix(10), viewPix(12), viewPix(12));
    }
    return _iconView;
}

-(UILabel *)durationLabel{
    if(!_durationLabel){
        _durationLabel = [UILabel lableWithText:@"" colorString:@"#FFFFFF" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
        _durationLabel.frame = CGRectMake(viewPix(26), 0, viewPix(60), viewPix(32));
    }
    return _durationLabel;
}

-(UIButton *)deleteBtn{
    if(!_deleteBtn){
        _deleteBtn = [UIButton buttonWithImage:@"处理意见-删除录音" selectImage:@"处理意见-删除录音"];
        _deleteBtn.frame = CGRectMake(viewPix(143), 0, viewPix(32), viewPix(32));
        [_deleteBtn addTarget:self action:@selector(deleteBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}

@end




